﻿using System;
using System.Linq.Expressions;

namespace NMortgage.UI.Tests
{
    static class ExpressionExtensions
    {
        public static string GetPropertyName<T>(this Expression<Func<T>> expression)
        {
            var exp = expression.Body as MemberExpression;
            return exp.Member.Name;
        }
        public static string GetPropertyName<TSubject,TProperty>(this Expression<Func<TSubject,TProperty>> expression)
        {
            var exp = expression.Body as MemberExpression;
            return exp.Member.Name;
        }
        public static Action<TSubject,TProperty> GetPropertySetter<TSubject,TProperty>(this Expression<Func<TSubject,TProperty>> expression)
        {
            var name = expression.GetPropertyName();

            var subjectVariable = Expression.Variable(typeof (TSubject), "s");
            var valueVariable = Expression.Variable(typeof (TProperty), "v");

            var propertyExp = Expression.Property(subjectVariable, name);

            var assignment = Expression.Assign(propertyExp, valueVariable);

            var lambdaExp = Expression.Lambda<Action<TSubject,TProperty>>(assignment, subjectVariable, valueVariable);

            return lambdaExp.Compile();
        }
    }
}
